/**
 * @author 0283000115
 * @date 2018年3月3日-下午2:32:37
 */
package com.zte.claa.inficombo.csa.app.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.zte.claa.inficombo.csa.app.controller.ret.ApiResult;
import com.zte.claa.inficombo.csa.app.service.csa.impl.BaseCacheManager;
import com.zte.claa.inficombo.csa.app.service.sapi.ffhost.FFCmdTarget;
import com.zte.claa.inficombo.csa.app.service.sapi.ffhost.FFTransDevCommand;
import com.zte.claa.inficombo.csa.app.service.sapi.ffhost.FFTransDevSAPIService;
import com.zte.claa.inficombo.csa.app.service.sapi.ffhost.bean.FFResDevBase;
import com.zte.claa.inficombo.csa.app.util.JsonUtils;
import com.zte.claa.inficombo.csa.app.util.SecurityUtil;

import io.swagger.annotations.ApiOperation;

/**
 * @author 0283000115
 * 
 * 消防传输装置和主机控制指令下发接口.
 */

@RestController
@RequestMapping("/csa/api/ff") 
public class CSAFFTransdevController extends BaseController {
	// logger
	private Logger logger = LoggerFactory.getLogger(CSAFFTransdevController.class);
	
	@Autowired 
	private FFTransDevSAPIService ffSapiService;
	
	@Autowired
	private BaseCacheManager cacheManager;
	
	/**
     * 传输装置指令下发
     * 
     * @param request
     * @return 
     * @throws Exception
     * 
     * 说明：
     * cmdcode = 4 （请求读取） 或 1 （时间同步）；
     * typeflag = 具体的请求类型（如61=消防设施系统状态，62=消防部件状态,...），详见GB规范.
     * extparas参数是一个map<String, Object>, key的取值参照消防传输装置国标规范定义，详见FFTransDevCommand全局变量定义。
     */
	@ApiOperation(value = "transDevCtrlCmd", notes = "")
	@RequestMapping(value={"/transDevCtrlCmd"}, method = RequestMethod.POST)
	@ResponseBody
	public ApiResult<?> transDevCtrlCmd(HttpServletRequest request) throws Exception{	
		String tokenStr = request.getParameter("token");
		ApiResult<?> ret1 = this.checkToken(tokenStr);
		if(ret1.isRetSucc() == false){
			return ret1;
		}	
		String transdeveui = request.getParameter("transdeveui");
		String cmdcode = request.getParameter("cmdcode");
		String typeflag = request.getParameter("typeflag");
		String extparas = request.getParameter("extparas");		
		logger.info("transDevCtrlCmd: transdeveui="+transdeveui+", cmdcode="+cmdcode+", typeflag="+typeflag+", extparas="+extparas);
		if(transdeveui.equals("")){
			throw new Exception("用户信息传输装置ID不能为空！");
		}
		FFTransDevCommand ffCommand = new FFTransDevCommand();
		ffCommand.setCmdcode(Integer.parseInt(cmdcode));
		ffCommand.setTypeflag(Integer.parseInt(typeflag));
		if(extparas != null && !extparas.equals("")){
			ffCommand.setParas(JsonUtils.jsonStrToHashMap(extparas));
		}
		this.ffSapiService.sendCommand(transdeveui, ffCommand);
		logger.info("Command is sent: "+ffCommand);
		ApiResult<String> ret = new ApiResult<String>();		
		ret.setData("");
		ret.setRemark("Command is sent.");
		ret.setResult(ApiResult.RET_SUCC);		
		return ret;
	}
	
	/**
     * 消防控制主机指令下发
     * 
     * @param request
     * @return 
     * @throws Exception
     * 
     */
	@ApiOperation(value = "hostDevCtrlCmd", notes = "")
	@RequestMapping(value={"/hostDevCtrlCmd"}, method = RequestMethod.POST)
	@ResponseBody
	public ApiResult<?> hostDevCtrlCmd(HttpServletRequest request) throws Exception{	
		String tokenStr = request.getParameter("token");
		ApiResult<?> ret1 = this.checkToken(tokenStr);
		if(ret1.isRetSucc() == false){
			return ret1;
		}	
		// 消防主机的资源ID列表，多个ID之间使用英文逗号分隔.
		String hostdeveuis = request.getParameter("hostdeveuis");
		String cmdcode = request.getParameter("cmdcode");
		String typeflag = request.getParameter("typeflag");
		String extparas = request.getParameter("extparas");		
		logger.info("transDevCtrlCmd: hostdeveuis="+hostdeveuis+", cmdcode="+cmdcode+", typeflag="+typeflag+", extparas="+extparas);
		if(hostdeveuis.equals("")){
			throw new Exception("消防设施系统ID不能为空！");
		}
		String transdevEui = null;
		String[] hostDevEuiArr = hostdeveuis.trim().split(",");
		List<FFCmdTarget> targetList = new ArrayList<FFCmdTarget>();
		for(String hostDevEui : hostDevEuiArr){
			FFResDevBase hostDev = this.cacheManager.getFFHostDevByEui(hostDevEui);
			if(hostDev == null){
				logger.warn("FFHostDev not exist: "+hostDevEui);
				throw new Exception("无效的消防设施系统编号: "+hostDevEui);
			}
			FFCmdTarget targetDev = new FFCmdTarget();
			targetDev.setTargettype(FFCmdTarget.TARGET_FFHOST);
			targetDev.setSysaddr(hostDev.getSysaddr());
			targetDev.setSystype(hostDev.getSystype());
			targetList.add(targetDev);
			// 确定对应的传输装置deveui...
			if(transdevEui == null){
				FFResDevBase transDev = this.cacheManager.getFFTransDevByAddr(hostDev.getTransdevaddr());
				if(transDev != null){
					transdevEui = transDev.getDeveui();
				}
			}
		}
		if(transdevEui == null){
			logger.warn("Not exist FFTransDev for FFHost: "+hostdeveuis);
			throw new Exception("未找到对应的用户信息传输装置！");
		}
		// 构造命令.
		FFTransDevCommand ffCommand = new FFTransDevCommand();
		ffCommand.setCmdcode(Integer.parseInt(cmdcode));
		ffCommand.setTypeflag(Integer.parseInt(typeflag));
		Map<String, Object> paraMap = new HashMap<String, Object>();
		paraMap.put(FFTransDevCommand.PARA_MAPKEY_TARGETS, targetList);
		if(extparas != null && !extparas.equals("")){
			paraMap.putAll(JsonUtils.jsonStrToHashMap(extparas));
		}
		// 执行命令.
		this.ffSapiService.sendCommand(transdevEui, ffCommand);
		logger.info("[2]Command is sent: "+ffCommand);
		ApiResult<String> ret = new ApiResult<String>();		
		ret.setData("");
		ret.setRemark("Command is sent.");
		ret.setResult(ApiResult.RET_SUCC);		
		return ret;
	}
	
	/**
     * 消防控制部件指令下发
     * 
     * @param request
     * @return 
     * @throws Exception
     * 
     */
	@ApiOperation(value = "hostPartDevCtrlCmd", notes = "")
	@RequestMapping(value={"/hostPartDevCtrlCmd"}, method = RequestMethod.POST)
	@ResponseBody
	public ApiResult<?> hostPartDevCtrlCmd(HttpServletRequest request) throws Exception{	
		String tokenStr = request.getParameter("token");
		ApiResult<?> ret1 = this.checkToken(tokenStr);
		if(ret1.isRetSucc() == false){
			return ret1;
		}	
		// 消防主机的资源ID列表，多个ID之间使用英文逗号分隔.
		String hostpartdeveuis = request.getParameter("hostpartdeveuis");
		String cmdcode = request.getParameter("cmdcode");
		String typeflag = request.getParameter("typeflag");
		String extparas = request.getParameter("extparas");		
		logger.info("transDevCtrlCmd: hostpartdeveuis="+hostpartdeveuis+", cmdcode="+cmdcode+", typeflag="+typeflag+", extparas="+extparas);
		if(hostpartdeveuis.equals("")){
			throw new Exception("消防设施部件ID不能为空！");
		}
		String transdevEui = null;
		String[] hostPartDevEuiArr = hostpartdeveuis.trim().split(",");
		List<FFCmdTarget> targetList = new ArrayList<FFCmdTarget>();
		for(String hostPartDevEui : hostPartDevEuiArr){
			FFResDevBase hostPartDev = this.cacheManager.getFFHostDevByEui(hostPartDevEui);
			if(hostPartDev == null){
				logger.warn("FFHostPartDev not exist: "+hostPartDevEui);
				throw new Exception("无效的消防设施部件编号: "+hostPartDevEui);
			}
			FFCmdTarget targetDev = new FFCmdTarget();
			targetDev.setTargettype(FFCmdTarget.TARGET_FFHOSTPART);
			targetDev.setSysaddr(hostPartDev.getSysaddr());
			targetDev.setSystype(hostPartDev.getSystype());
			targetDev.setPartaddr(SecurityUtil.parseHexStr2Byte(hostPartDev.getPartaddr()));
			targetDev.setParttype(hostPartDev.getParttype());			
			targetList.add(targetDev);
			// 确定对应的传输装置deveui...
			if(transdevEui == null){
				FFResDevBase transDev = this.cacheManager.getFFTransDevByAddr(hostPartDev.getTransdevaddr());
				if(transDev != null){
					transdevEui = transDev.getDeveui();
				}
			}
		}
		if(transdevEui == null){
			logger.warn("Not exist FFTransDev for FFHost: "+hostpartdeveuis);
			throw new Exception("未找到对应的用户信息传输装置！");
		}
		// 构造命令.
		FFTransDevCommand ffCommand = new FFTransDevCommand();
		ffCommand.setCmdcode(Integer.parseInt(cmdcode));
		ffCommand.setTypeflag(Integer.parseInt(typeflag));
		Map<String, Object> paraMap = new HashMap<String, Object>();
		paraMap.put(FFTransDevCommand.PARA_MAPKEY_TARGETS, targetList);
		if(extparas != null && !extparas.equals("")){
			paraMap.putAll(JsonUtils.jsonStrToHashMap(extparas));
		}
		// 执行命令.
		this.ffSapiService.sendCommand(transdevEui, ffCommand);
		logger.info("[3]Command is sent: "+ffCommand);
		ApiResult<String> ret = new ApiResult<String>();		
		ret.setData("");
		ret.setRemark("Command is sent.");
		ret.setResult(ApiResult.RET_SUCC);		
		return ret;
	}	
	
}
